package com.axing.aiguideagent.controller;

import cn.hutool.core.io.FileUtil;
import com.axing.aiguideagent.constant.FileConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 文件下载控制器
 * 提供PDF等文件的下载服务
 * 
 * 注意：application.yml中已设置 context-path: /api
 * 所以这里不需要再加 /api 前缀
 * 
 * CORS配置在全局 CorsConfig 中统一处理
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    /**
     * 下载PDF文件
     *
     * @param fileName PDF文件名
     * @return 文件流
     */
    @GetMapping("/pdf/download")
    public ResponseEntity<Resource> downloadPDF(@RequestParam String fileName) {
        try {
            // 确保文件名安全，防止路径遍历攻击
            String safeFileName = new File(fileName).getName();
            String filePath = FileConstant.FILE_SAVE_DIR + "/pdf/" + safeFileName;
            File file = new File(filePath);

            if (!file.exists() || !file.isFile()) {
                log.warn("PDF文件不存在: {}", filePath);
                return ResponseEntity.notFound().build();
            }

            // 创建文件资源
            Resource resource = new FileSystemResource(file);

            // 对文件名进行URL编码，支持中文文件名
            String encodedFileName = URLEncoder.encode(safeFileName, StandardCharsets.UTF_8.toString())
                    .replace("+", "%20");

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName);
            headers.setContentType(MediaType.APPLICATION_PDF);
            headers.setContentLength(file.length());

            log.info("开始下载PDF文件: {}", safeFileName);
            return new ResponseEntity<>(resource, headers, HttpStatus.OK);
        } catch (UnsupportedEncodingException e) {
            log.error("文件名编码失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        } catch (Exception e) {
            log.error("下载PDF文件时发生错误", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 预览PDF文件（在浏览器中直接打开）
     *
     * @param fileName PDF文件名
     * @return 文件流
     */
    @GetMapping("/pdf/preview")
    public ResponseEntity<Resource> previewPDF(@RequestParam String fileName) {
        try {
            // 确保文件名安全，防止路径遍历攻击
            String safeFileName = new File(fileName).getName();
            String filePath = FileConstant.FILE_SAVE_DIR + "/pdf/" + safeFileName;
            File file = new File(filePath);

            if (!file.exists() || !file.isFile()) {
                log.warn("PDF文件不存在: {}", filePath);
                return ResponseEntity.notFound().build();
            }

            // 创建文件资源
            Resource resource = new FileSystemResource(file);

            // 对文件名进行URL编码，支持中文文件名
            String encodedFileName = URLEncoder.encode(safeFileName, StandardCharsets.UTF_8.toString())
                    .replace("+", "%20");

            // 设置响应头为inline，浏览器将尝试打开而不是下载
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename*=UTF-8''" + encodedFileName);
            headers.setContentType(MediaType.APPLICATION_PDF);
            headers.setContentLength(file.length());

            log.info("预览PDF文件: {}", safeFileName);
            return new ResponseEntity<>(resource, headers, HttpStatus.OK);
        } catch (UnsupportedEncodingException e) {
            log.error("文件名编码失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        } catch (Exception e) {
            log.error("预览PDF文件时发生错误", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 获取PDF列表
     *
     * @return PDF文件列表
     */
    @GetMapping("/pdf/list")
    public ResponseEntity<?> listPDFs() {
        try {
            String pdfDir = FileConstant.FILE_SAVE_DIR + "/pdf";
            File dir = new File(pdfDir);

            log.info("查询PDF目录: {}", pdfDir);

            if (!dir.exists() || !dir.isDirectory()) {
                log.warn("PDF目录不存在: {}", pdfDir);
                return ResponseEntity.ok(new String[]{});
            }

            File[] files = dir.listFiles((d, name) -> name.toLowerCase().endsWith(".pdf"));
            if (files == null || files.length == 0) {
                log.info("PDF目录为空");
                return ResponseEntity.ok(new String[]{});
            }

            String[] fileNames = new String[files.length];
            for (int i = 0; i < files.length; i++) {
                fileNames[i] = files[i].getName();
            }

            log.info("找到 {} 个PDF文件", fileNames.length);
            return ResponseEntity.ok(fileNames);
        } catch (Exception e) {
            log.error("获取PDF列表失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取PDF列表失败");
        }
    }
    
    /**
     * 测试端点 - 检查文件服务是否正常
     */
    @GetMapping("/test")
    public ResponseEntity<?> testEndpoint() {
        String pdfDir = FileConstant.FILE_SAVE_DIR + "/pdf";
        File dir = new File(pdfDir);
        
        return ResponseEntity.ok(java.util.Map.of(
            "status", "OK",
            "message", "文件服务正常运行",
            "pdfDirectory", pdfDir,
            "directoryExists", dir.exists(),
            "isDirectory", dir.isDirectory(),
            "absolutePath", dir.getAbsolutePath()
        ));
    }
}

